import express, { Request, Response, Router } from 'express';
import { PrismaClient } from '@prisma/client';
import { authMiddleware } from '../middleware/auth';
import { ApiResponse } from '../utils/response';
import { priceService } from '../services/priceService';

const router: Router = express.Router();
const prisma = new PrismaClient();

// 获取默认质押产品信息（需要认证，显示用户等级的收益率）
router.get('/product', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;

    // 获取用户信息和等级
    const user = await prisma.user.findUnique({
      where: { id: userId },
      select: { tier: true }
    });

    if (!user) {
      res.status(404).json(ApiResponse.error('사용자를 찾을 수 없습니다.'));
      return;
    }

    // 获取用户当前等级的配置
    const tierConfig = await prisma.tierConfig.findUnique({
      where: { tier: user.tier }
    });

    if (!tierConfig) {
      res.status(404).json(ApiResponse.error('등급 구성을 찾을 수 없습니다.'));
      return;
    }

    // 获取NEAR-STANDARD产品基础信息
    const product = await prisma.stakingProduct.findUnique({
      where: { symbol: 'NEAR-STANDARD' }
    });

    if (!product) {
      res.status(404).json(ApiResponse.error('기본 스테이킹 상품을 찾을 수 없습니다.'));
      return;
    }

    // 使用用户等级的收益率覆盖产品默认收益率
    const productData = {
      id: product.id,
      name: product.name,
      symbol: product.symbol,
      iconUrl: product.iconUrl,
      dailyRewardRate: Number(tierConfig.dailyRate), // 使用用户等级的日收益率
      fixedApr: Number(tierConfig.annualRate), // 使用用户等级的年收益率
      minStakeAmount: Number(tierConfig.minInvestment), // 使用用户等级的最小投资额
      maxStakeAmount: product.maxStakeAmount ? Number(product.maxStakeAmount) : null,
      stakingPeriodDays: product.stakingPeriodDays,
      description: product.description,
      isActive: product.isActive,
      userTier: user.tier // 添加用户当前等级信息
    };

    res.json(ApiResponse.success(productData, '스테이킹 상품 정보를 성공적으로 불러왔습니다.'));
  } catch (error) {
    console.error('스테이킹 상품 정보 조회 오류:', error);
    res.status(500).json(ApiResponse.error('스테이킹 상품 정보를 불러오지 못했습니다.'));
  }
});

// 获取质押概览
router.get('/overview', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;

    // 获取传统NEAR质押信息
    const stakingInfo = await prisma.userStaking.findFirst({
      where: { userId }
    });

    const lockedNear = Number(stakingInfo?.lockedAmount || 0);
    const stakedNear = Number(stakingInfo?.stakedAmount || 0);

    // 获取NEAR价格
    const nearPrice = await priceService.getNearPrice();

    // 使用用户当前的日收益率计算 B × C
    const dailyRate = Number(stakingInfo?.dailyRewardRate ?? 0);
    const totalStakingBase = stakedNear;
    const dailyRewardNEAR = totalStakingBase * dailyRate;
    const dailyRewardKRW = dailyRewardNEAR * nearPrice;

    // 将日收益率折算成年化收益率（以百分数表示）
    const annualYield = dailyRate * 365 * 100;

    // 获取传统NEAR质押累计奖励
    const totalRewardsNEAR = Number(stakingInfo?.totalRewardsNear || 0);
    const totalRewardsKRW = totalRewardsNEAR * nearPrice;

    // 只返回传统NEAR质押数据
    const stakingData = {
      lockedNear,           // 锁定的NEAR（推荐奖励）
      stakedNear,           // 质押的NEAR本金
      dailyRewardKRW,       // NEAR质押日收益KRW
      dailyRewardNEAR,      // NEAR质押日收益NEAR
      totalRewardsKRW,      // 总收益KRW
      totalRewardsNEAR,     // 总收益NEAR
      annualYield
    };

    res.json(ApiResponse.success(stakingData, '스테이킹 개요 조회에 성공했습니다.'));
  } catch (error) {
    console.error('스테이킹 개요 조회 오류:', error);
    res.status(500).json(ApiResponse.error('스테이킹 개요 조회에 실패했습니다.'));
  }
});

// 获取质押奖励信息
router.get('/rewards', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;

    // 获取质押信息
    const stakingInfo = await prisma.userStaking.findFirst({
      where: { userId }
    });

    // 获取用户余额
    const userBalance = await prisma.userBalance.findUnique({
      where: { userId }
    });

    const nearPrice = await priceService.getNearPrice();

    // D: 累计质押收益：按历史结算金额统计，避免汇率波动造成差异
    const settlementSum = await prisma.stakingSettlement.aggregate({
      where: { userId },
      _sum: {
        rewardKrw: true,
        rewardNear: true
      }
    });
    const aggregatedRewardsKrw = Number(settlementSum._sum.rewardKrw || 0);
    const aggregatedRewardsNear = Number(settlementSum._sum.rewardNear || 0);

    const storedTotalRewardsNear = Number(stakingInfo?.totalRewardsNear || 0);
    const totalRewardsNear = storedTotalRewardsNear > 0 ? storedTotalRewardsNear : aggregatedRewardsNear;
    const totalRewardsKrw = totalRewardsNear * nearPrice;

    const availableRewardsKrw = Number(userBalance?.balance || 0);
    const availableRewardsNear = nearPrice > 0
      ? Number((availableRewardsKrw / nearPrice).toFixed(6))
      : 0;

    // E: 质押本金
    const stakedAmount = Number(stakingInfo?.stakedAmount || 0);

    // 日收益率
    const dailyRate = Number(stakingInfo?.dailyRewardRate || 0.02);

    // 预计今日收益（仅依据质押本金）
    const totalStakingBase = stakedAmount;
    const expectedDailyRewardNear = totalStakingBase * dailyRate;
    const expectedDailyRewardKrw = expectedDailyRewardNear * nearPrice;

    // 质押天数
    const stakingPeriod = stakingInfo?.createdAt
      ? Math.floor((Date.now() - stakingInfo.createdAt.getTime()) / (1000 * 60 * 60 * 24))
      : 0;

    const stakingRewards = {
      totalRewards: totalRewardsKrw, // D的KRW价值 (Box 2/4/5显示，历史累计)
      totalRewardsNear, // D的NEAR数量（历史累计，只增不减）

      availableRewards: availableRewardsKrw, // 可提取KRW (Box 3/6显示，按账面收益转换)
      availableRewardsNear, // 可提取NEAR（基于账面累计收益）

      lockedRewards: 0, // 不再有锁定收益概念

      dailyRewards: expectedDailyRewardKrw, // 预计每日收益KRW
      dailyRewardsNear: expectedDailyRewardNear, // 预计每日收益NEAR

      apy: dailyRate * 365 * 100, // 年化收益率(%)
      dailyRate: dailyRate * 100, // 日收益率(%)
      stakingPeriod
    };

    res.json(ApiResponse.success(stakingRewards, '스테이킹 보상 조회에 성공했습니다.'));
  } catch (error) {
    console.error('스테이킹 보상 조회 오류:', error);
    res.status(500).json(ApiResponse.error('스테이킹 보상 조회에 실패했습니다.'));
  }
});

// 获取质押历史
router.get('/history', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;
    const { page = 1, limit = 20 } = req.query;

    // 获取质押操作记录
    const stakingHistory = await prisma.stakingHistory.findMany({
      where: { userId },
      orderBy: { createdAt: 'desc' },
      skip: (Number(page) - 1) * Number(limit),
      take: Number(limit)
    });

    // 获取奖励记录
    const rewardHistory = await prisma.stakingReward.findMany({
      where: { userId },
      orderBy: { createdAt: 'desc' },
      skip: (Number(page) - 1) * Number(limit),
      take: Number(limit)
    });

    // 合并记录
    const allHistory = [
      ...stakingHistory.map(h => ({
        id: `staking_${h.id}`,
        type: h.type,
        amount: Number(h.amount),
        currency: 'NEAR',
        status: 'completed',
        timestamp: h.createdAt.getTime(),
        txHash: h.txHash
      })),
      ...rewardHistory.map(r => ({
        id: `reward_${r.id}`,
        type: 'reward',
        amount: Number(r.amount),
        currency: 'NEAR',
        status: 'completed',
        timestamp: r.createdAt.getTime(),
        txHash: r.txHash
      }))
    ].sort((a, b) => b.timestamp - a.timestamp);

    res.json(ApiResponse.success({
      transactions: allHistory.slice(0, Number(limit)),
      pagination: {
        page: Number(page),
        limit: Number(limit),
        total: allHistory.length
      }
    }, '스테이킹 내역 조회에 성공했습니다.'));
  } catch (error) {
    console.error('스테이킹 내역 조회 오류:', error);
    res.status(500).json(ApiResponse.error('스테이킹 내역 조회에 실패했습니다.'));
  }
});

// 提取质押奖励（已废弃 - 收益自动转入余额，使用统一提现功能）
router.post('/withdraw', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  // 此功能已废弃：质押收益现在自动结算到用户余额
  // 用户应使用统一的提现功能 /api/withdraw/apply
  res.status(410).json(ApiResponse.error(
    '스테이킹 보상은 이제 자동으로 잔액에 정산됩니다. 출금 페이지(/withdraw)에서 통합 출금 기능을 사용해 주세요.'
  ));
});

// 获取质押性能指标
router.get('/performance', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    // 这些数据可以是全局的验证者信息
    const performance = {
      validatorRank: 15,
      validatorName: 'NEAR Korea',
      uptime: 99.8,
      commission: 5.0,
      delegators: 1247,
      totalStaked: 125000000 // KRW
    };

    res.json(ApiResponse.success(performance, '스테이킹 성능 지표 조회에 성공했습니다.'));
  } catch (error) {
    console.error('스테이킹 성능 지표 조회 오류:', error);
    res.status(500).json(ApiResponse.error('스테이킹 성능 지표 조회에 실패했습니다.'));
  }
});

export default router;
